package com.pic.mgt.monitor.parser.haishin;

import java.io.File;

import com.pic.mgt.monitor.WrongUnitFormatException;
import com.pic.mgt.monitor.parser.FormatParser;

public final class AppointedConfirmationFileForTxFileParser extends
		FormatParser {
	private int messageTerminalIdStartFromChar;
	private char[] haishinOutboxPublicStrCharArray;
	private int messageFilenameLen;
	private String businessConfirmationFilenameSuffix;
	
	public AppointedConfirmationFileForTxFileParser(String haishinOutboxPublicStr) {
		this.haishinOutboxPublicStrCharArray = haishinOutboxPublicStr.toCharArray();
	}

	@Override
	public Object parse(Object _confirmationFile) throws WrongUnitFormatException {
		// 確認是否為 File 型態
		// throws WrongUnitFormatException
		super.checkObjectType(_confirmationFile, File.class);
		
		File confirmationFile = (File)_confirmationFile;
		
		// 取得 confirmation file 路徑(不含檔名)
		String confirmationFileParentFileStr = confirmationFile.getParentFile().getAbsolutePath();
		if (null == confirmationFileParentFileStr) {
			throw new WrongUnitFormatException(
					"The confirmation file '" + confirmationFile.getAbsolutePath() +
					"' of message is not correct!");
		}
		
		// 取得訊息確認檔檔名(不含Suffix)
		String confirmationFilenameWithoutSuffix;
		try {
			confirmationFilenameWithoutSuffix =  confirmationFile.getName().substring(0, messageFilenameLen);
		} catch (IndexOutOfBoundsException e1) {
			throw new WrongUnitFormatException(
					"The confirmation filename '" + confirmationFile.getName() +
					"' of message is not correct!");
		}
		
		// 取得交易檔的確認檔(不含Suffix)
		int pos = this.messageTerminalIdStartFromChar;
		char[] confirmationFilenameWithoutSuffixCharArray = confirmationFilenameWithoutSuffix.toCharArray();
		try {
			for (int i=0;i<this.haishinOutboxPublicStrCharArray.length;i++) {
				confirmationFilenameWithoutSuffixCharArray[pos - 1] = this.haishinOutboxPublicStrCharArray[i];
			}
		} catch (IndexOutOfBoundsException e) {
			throw new WrongUnitFormatException(
					"The confirmation filename '" + confirmationFile.getName() +
					"' of message is not correct!");
		}
		String confirmationFilenameForTxFileWithoutSuffix = new String(confirmationFilenameWithoutSuffixCharArray);
		
		return new File(confirmationFileParentFileStr,
				        confirmationFilenameForTxFileWithoutSuffix + businessConfirmationFilenameSuffix);
	}
	
	// --- getter and setter ---

	public void setMessageTerminalIdStartFromChar(int messageTerminalIdStartFromChar) {
		this.messageTerminalIdStartFromChar = messageTerminalIdStartFromChar;
	}

	public void setMessageFilenameLen(int messageFilenameLen) {
		this.messageFilenameLen = messageFilenameLen;
	}

	public void setBusinessConfirmationFilenameSuffix(
			String businessConfirmationFilenameSuffix) {
		this.businessConfirmationFilenameSuffix = businessConfirmationFilenameSuffix;
	}

}
